/* eslint-disable consistent-return */
/* eslint-disable no-case-declarations */
const fs = require('fs');
// const path = require('path')
const yargs = require('yargs')
const ci = require('miniprogram-ci')
const git = require('git-last-commit');
const pkgVersion = require('../package.json').version
const { argv } = yargs
const APP_TYPE = argv.apptype || 'hz'

// 开发版: yarn deploy -- --type=develop --v=1.1.1 --robot=1 --desc=我是描述
// 体验版: yarn deploy -- --type=trial --v=1.0.1 --robot=1 --desc=我是描述

// node deploy.js -- --type=develop --v=1.1.1 --robot=1 --desc=我是描述

const APP_DEPLOY_MAPPING = {
  hn: {
    appId: 'wx34a512170b1d4b8e',
    keyPath: './deploy/hn_private.wx34a512170b1d4b8e.key'
  },
  hz: {
    appId: 'wxd38e08a1e7840dd1',
    keyPath: './deploy/private.wxd38e08a1e7840dd1.key'
  }
}
const project = new ci.Project({
  appid: APP_DEPLOY_MAPPING[APP_TYPE].appId,
  type: 'miniProgram',
  projectPath: './dist/weapp',
  privateKeyPath: APP_DEPLOY_MAPPING[APP_TYPE].keyPath,
  ignores: ['node_modules/**/*'],
})
// console.log(project)
async function run(message) {
  const {
    type = 'develop', robot = 2, tag, apptype
  } = argv; // v: version,
  const version = pkgVersion
  console.log(`apptype: ${apptype}`);
  console.log(`tag: ${tag}`);
  console.log(`type: ${type}`);
  console.log(`version: ${version}`);
  console.log(`desc: ${message}`);
  console.log(`robot: ${robot}`);

  const coverJPG2Base64 = () => {
    const filename = `./deploy/qrcode/preview-qrcode-v${version}.jpg`
    const bData = fs.readFileSync(filename);
    const base64Str = bData.toString('base64');
    const datauri = `data:image/png;base64,${base64Str}`;

    const html = `<html><body><img src="${datauri}" /><h1>${message}</h1><h2>${new Date().toLocaleString()}</h2><h2>${version}</h2></body></html>`
    fs.writeFile('./dist/preview.html', html, err => {
      if (err) return console.log(err);
      console.log('Wirte preview successfuly');
    });
  }

  // const warning = await ci.packNpmManually({
  //   packageJsonPath: './package.json',
  //   miniprogramNpmDistDir: './dist/weapp/',
  // });

  // const warning = await ci.packNpm(project, {
  //   // ignores: ['pack_npm_ignore_list'],
  //   reporter: infos => { console.log(infos) }
  // })

  console.log('构建NPM成功')
  const tagmsg = `${tag}: ${message}`
  const defaults = {
    project,
    message,
    desc: tagmsg,
    setting: {
      es6: false,
      urlCheck: true,
      postcss: false,
      minified: false
    },
    // onProgressUpdate: console.log,
  };

  // console.log()

  switch (type) {
    case 'develop':
      const previewConfig = {
        ...defaults,
        qrcodeFormat: 'image',
        qrcodeOutputDest: `./deploy/qrcode/preview-qrcode-v${version}.jpg`,
        robot,
      };
      await ci.preview(previewConfig);
      // setTimeout(function() {
      coverJPG2Base64()
      // }, 5000);
      break;
    case 'trial':
      const uploadConfig = {
        ...defaults,
        version,
        robot: 1,
      };
      await ci.upload(uploadConfig);
      break;
    default:
      break;
  }

  // // 这一步会报错
  // await ci.upload({
  //   project,
  //   version: '1.1.1',
  //   desc: 'hello',
  //   setting: {
  //     es6: true,
  //   },
  //   onProgressUpdate: console.log,
  // })
  console.log('上传成功')
}

git.getLastCommit((err, commit) => {
  console.log(`${commit.committer.name} - ${commit.subject}`);
  run(`${commit.committer.name} - ${APP_TYPE} 2020-09-08 Release Prod`)
});

